﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    public class ProxyAuditController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;
        private readonly SmtpSettings _emailSender;

        public ProxyAuditController(mtContext context, IWebHostEnvironment hostingEnv, SmtpSettings emailSender) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
            _emailSender = emailSender;
        }

        #region 列表       
        public IActionResult Index()
        {
            return View();
        }


        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, string account, string currentReviewer, string createDate, string field, string order, int type = -1, int state = -1)
        {

            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.Promotions
                           join c in _context.CrmUsers on y.CrmId equals c.Id
                           join d in _context.Mt5Users on c.Id equals d.CrmId into dd
                           from dddata in dd.DefaultIfEmpty()
                           select new
                           {
                               index = y.Id,
                               id = y.CrmId,
                               fullName = c.Name,
                               loginName = c.LoginName,
                               state = y.State,
                               createDate = y.CreateDate,
                               currentReviewer = y.Reviewer,
                               endTime = y.OverDate,
                               tradingAccount = dddata.Login.ToString() == null ? 0 : dddata.Login
                           };
                //姓/名/账户ID
                if (!string.IsNullOrEmpty(account))
                {
                    long loginNo = 0;
                    try
                    {
                        loginNo = Convert.ToInt64(account);
                    }
                    catch
                    {
                        loginNo = 0;
                    }
                    if (loginNo == 0)
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account));
                    }
                    else
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account) || k.tradingAccount == loginNo);
                    }
                
                }
                if (!string.IsNullOrEmpty(currentReviewer))
                {
                    data = data.Where(k => k.currentReviewer.Contains(currentReviewer));
                }
                if (!string.IsNullOrEmpty(createDate) && createDate.Contains(" - "))
                {
                    string[] createDates = createDate.Split(new string[] { " - " }, StringSplitOptions.None);
                    DateTime startTime = Convert.ToDateTime(createDates[0]);
                    DateTime endTime = Convert.ToDateTime(createDates[1]);
                    data = data.Where(k => k.createDate > startTime && k.createDate < endTime);
                }
                if (state > -1)
                {
                    data = data.Where(k => k.state == state);
                }

                if (!string.IsNullOrEmpty(field))
                {
                    if (string.IsNullOrEmpty(order))
                    {
                        data = data.OrderBy(k => field).ThenBy(k => k.index);
                    }
                    else if (order == "asc")
                    {
                        data = data.OrderBy(k => field);
                    }
                    else
                    {
                        data = data.OrderByDescending(k => field);
                    }

                }
                else
                {
                    data = data.OrderBy(k => k.state).ThenByDescending(k => k.createDate);
                }
                res.Count = data.Count();

                res.Data = await data.Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                res.Code = 0;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }

        }
        #endregion

        #region 代理审核详情
        public async Task<IActionResult> Detail(int id)
        {

            #region 用户申请记录
            Promotion promotion = await _context.Promotions.FindAsync(id);
            if (promotion == null)
            {
                return NotFound();
            }
            ViewBag.promotions = promotion;
            #endregion

            #region 账户信息
            CrmUser crmUser = await _context.CrmUsers.FindAsync(promotion.CrmId);
            if (crmUser == null)
            {
                return NotFound();
            }
            ViewBag.crmUsers = crmUser;
            #endregion

            #region 个人信息
            CrmUserInfo userInfo = _context.CrmUserInfos.FirstOrDefault(k => k.CrmId == promotion.CrmId && k.Type == 1 && k.State == 2);

            if (userInfo != null)
            {
                ViewBag.userInfos = userInfo;
                //个人信息
                if (!string.IsNullOrEmpty(userInfo.Personal))
                {

                    #region 个人信息                 

                    List<CrmKyc> personalInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(userInfo.Personal);
                    ViewBag.personalInformations = personalInformations;
                    #endregion
                }
                else
                {
                    ViewBag.personalInformations = null;
                }

            }
            #endregion

            #region 审核记录

            var data = from y in _context.CrmAuditLogs
                       join c in _context.TbUsers on y.ReviewerId equals c.Id into cc
                       from ccdata in cc.DefaultIfEmpty()
                       join d in _context.CrmUsers on y.CrmId equals d.Id
                       select new CrmAuditLog
                       {
                           Id = y.Id,
                           OrderId = y.OrderId,
                           CrmId = y.CrmId,
                           Type = y.Type,
                           Cont = y.Cont,
                           Remark = y.Remark,
                           Reviewer = y.ReviewerId != null ? ccdata.UserName : d.Name,
                           CreateDate = y.CreateDate,
                           ReviewerId = y.ReviewerId

                       };
            var crmAuditLogs = data.Where(k => k.OrderId == promotion.Id.ToString() && k.Type == 7).OrderBy(p => p.Id).ToList();
            ViewBag.crmAuditLogsList = crmAuditLogs;
            #endregion

            #region 登录用户名
            ViewBag.LoginName = User.UserName;
            #endregion

            return View(crmUser);
        }
        #endregion

        #region 保存审核信息
        [HttpPost]
        public async Task<JsonResult> Edit(int Id, int State, string Remarks, string Reviewer, int programme)
        {
            Result res = new Result();
            try
            {
                if (State == 0)
                {
                    res.Code = 1;
                    res.Msg = "incompleteInformation";
                    return new JsonResult(res);
                }
                #region 获取代理申请
                Promotion promotion = await _context.Promotions.FindAsync(Id);
                if (promotion == null)
                {
                    res.Code = 1;
                    res.Msg = "gettingInformationFailure";
                    return new JsonResult(res);

                }
                #endregion

                if (State == 2)
                {
                    #region 修改crm用户返佣方案
                    CrmUser tbUser = await _context.CrmUsers.FindAsync(promotion.CrmId);
                    tbUser.SchemeId = programme;
                    tbUser.Role = 1;
                    #endregion
                }

                #region 修改代理申请
                promotion.State = State;
                promotion.OverDate= DateTimeUtil.Now;
                promotion.Reviewer = Reviewer;
                promotion.Remarks = Remarks;
                #endregion

                #region 新增审核记录
                CrmAuditLog crmAuditLog = new CrmAuditLog();
                crmAuditLog.OrderId = promotion.Id.ToString();
                crmAuditLog.CrmId = promotion.CrmId;
                crmAuditLog.Type = 7;
                if (State == 2)
                    crmAuditLog.Cont = "审核通过";
                else
                    crmAuditLog.Cont = "审核拒绝";
                crmAuditLog.Reviewer = User.UserName;
                crmAuditLog.ReviewerId = User.Id;
                crmAuditLog.CreateDate = DateTimeUtil.Now;
                _context.Add(crmAuditLog);
                #endregion


                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);


            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);

            }

        }
        #endregion

    }
}
